package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.CacheHelper;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.OrderRecode;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import com.baomidou.mybatisplus.extension.api.R;
import com.sun.corba.se.spi.servicecontext.UEInfoServiceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author: zm
 * @Date: 2021/8/31 20:56
 */
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckilApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/findAll")
    public Result findAll() {
        List<SeckillGoods> list = seckillGoodsService.findAll();
        return Result.ok(list);
    }

    @GetMapping("/getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable Long skuId) {
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
        return Result.ok(seckillGoods);
    }

    // /api/activity/seckill/auth/getSeckillSkuIdStr/52
    // 获取下单码
    @GetMapping("auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request) {
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
        String userId = AuthContextHolder.getUserId(request);
        //
        if (!StringUtils.isEmpty(userId) && seckillGoods != null) {
            if (DateUtil.dateCompare(seckillGoods.getStartTime(), new Date()) &&
                    DateUtil.dateCompare(new Date(), seckillGoods.getEndTime())) {

                String skuIdStr = MD5.encrypt(userId); // MD5 加密
                return Result.ok(skuIdStr); // 返回数据
            }
        }
        return Result.fail().message("获取下单码失败");
    }

    // '/auth/seckillOrder/' + skuId + '?skuIdStr=' + skuIdStr,
    // 预下单
    @PostMapping("auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
//        DigestUtils.md5DigestAsHex(userId.getBytes()); MD5 加密
        String skuIdStr = request.getParameter("skuIdStr");
        if (!skuIdStr.equals(MD5.encrypt(userId))) {
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
        // 从内存中渠道 状态位
        String status = (String) CacheHelper.get(skuId.toString());
        if (StringUtils.isEmpty(status)) {
            // 状态位 返回非法参数
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        } else if ("0".equals(status)) {
            // 状态位为 0 返回已售罄
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        } else if ("1".equals(status)) {
            // 状态位为 1  可以进行秒杀 将秒杀的人与商品发送到队列中！
            //  消息的内容： 人 商品 封装到一个对象中！
            UserRecode userRecode = new UserRecode();
            userRecode.setSkuId(skuId);
            userRecode.setUserId(userId);
            // 发送消息 到队列中 监听秒杀
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER, MqConst.ROUTING_SECKILL_USER, userRecode);
            return Result.ok();
        } else {
            // 其他 返回非法参数
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
    }

    // '/auth/checkOrder/' + skuId
    // 检测订单状态
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        return seckillGoodsService.checkOrder(skuId, userId);
    }


    // 显示秒杀订单详情
    // userAddressList  detailArrayList  totalNum  totalAmount
    @GetMapping("auth/trade")
    public Result trade(HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);

        OrderRecode orderRecode = (OrderRecode) redisTemplate.opsForHash().get(RedisConst.SECKILL_ORDERS, userId);
        if (orderRecode == null) {
            return Result.fail().message("订单页面显示失败....");
        }

        SeckillGoods seckillGoods = orderRecode.getSeckillGoods();

        List<OrderDetail> detailArrayList = new ArrayList<>();
        //  声明一个订单明细对象
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setSkuNum(orderRecode.getNum());
        orderDetail.setSkuId(seckillGoods.getSkuId());
        orderDetail.setSkuName(seckillGoods.getSkuName());
        orderDetail.setImgUrl(seckillGoods.getSkuDefaultImg());
        orderDetail.setOrderPrice(seckillGoods.getCostPrice());
        detailArrayList.add(orderDetail);

        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(Long.parseLong(userId));

        Map<String, Object> map = new HashMap<>();
        map.put("detailArrayList", detailArrayList);
        map.put("userAddressList", userAddressList);
        map.put("totalNum", orderRecode.getNum());
        map.put("totalAmount", seckillGoods.getCostPrice());

        return Result.ok(map);
    }

    //    '/auth/submitOrder'
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderFeignClient.submitOrder(orderInfo);
        if (orderId == null) {
            return Result.fail().message("订单生产失败...");
        }

        // 删除预下单数据
//        redisTemplate.opsForHash().delete(RedisConst.SECKILL_ORDERS, userId);
        redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).delete(userId);
        // 保存下单数据到redis
        redisTemplate.opsForHash().put(RedisConst.SECKILL_ORDERS_USERS, userId, orderId.toString());

        return Result.ok(orderId);
    }

}
